package com.wardrobe.soa.api.shop;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.wardrobe.dao.booking.BookingDao;
import com.wardrobe.dao.goods.GoodsDao;
import com.wardrobe.dao.shop.ShopDao;
import com.wardrobe.domain.booking.BookingShowBean;
import com.wardrobe.domain.goods.GoodsShowBean;
import com.wardrobe.domain.shop.ShopSaveBean;
import com.wardrobe.domain.shop.ShopShowBean;
import com.wardrobe.soa.common.WeChatConsant;
import com.wardrobe.soa.utils.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/11/16.
 */
@Service
public class ShopService {
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private BookingDao bookingDao;
    @Autowired
    private GoodsDao goodsDao;

    public int saveShop(ShopSaveBean bean){
        Gson gson = new Gson();
//        ShopSaveBean bean = gson.fromJson(shopJson, ShopSaveBean.class);
       if(StringUtils.isNotBlank(bean.getAddress())){
            String location = HttpClientUtils.httpGetBodyUTF8(WeChatConsant.locationUrl + bean.getAddress());
            Map<String,Object> locationMap = gson.fromJson(location, Map.class);
            if(locationMap !=null && locationMap.get("message").equals("query ok")){
                LinkedTreeMap lacData = (LinkedTreeMap) locationMap.get("result");
                LinkedTreeMap lacMap = (LinkedTreeMap) lacData.get("location");
                bean.setLongitude(String.valueOf(lacMap.get("lng")));
                bean.setLatitude(String.valueOf(lacMap.get("lat")));
            }
        }
        ShopShowBean shopBean = shopDao.selectShopByUserId(bean.getUserId());
        if(shopBean == null){
            int flag = shopDao.insertShop(bean);
            return flag;
        }else{
            return -1;
        }
    }

    public ShopShowBean shopDetail(long id){
        return shopDao.selectShopById(id);
    }

    public  LinkedTreeMap getLngLat(String address){
        Gson gson = new Gson();
        String location = HttpClientUtils.httpGetBodyUTF8(WeChatConsant.locationUrl + address);
        Map<String,Object> locationMap = gson.fromJson(location, Map.class);
        if(locationMap !=null && locationMap.get("message").equals("query ok")){
            LinkedTreeMap lacData = (LinkedTreeMap) locationMap.get("result");
            LinkedTreeMap lacMap = (LinkedTreeMap) lacData.get("location");
           return lacMap;
        }
        return null;
    }

    public List<BookingShowBean> getBookingListByShopId(long shopId){
        return bookingDao.selectBookingByShopId(shopId);
    }

    public List<GoodsShowBean> getGoodsListByShopId(long shopId){
        return goodsDao.selectGoodsListByShopId(shopId);
    }
    
}
